package com.iwithlong.utils;

import com.chenlb.mmseg4j.Dictionary;
import com.chenlb.mmseg4j.analysis.SimpleAnalyzer;
import com.imesne.assistant.common.utils.PropertyUtils;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.search.*;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

import java.io.File;
import java.io.IOException;

/**
 * Lucene 全文搜索引擎
 * <p>
 * User: TJM
 * Date: 2017/10/13 11:17
 * version $Id: LuceneContext.java, v 0.1  11:17 Exp $
 */
public class LuceneContext {

	private static LuceneContext instance;
	private static IndexWriter writer;
	private static Analyzer analyzer;
	private static Version version;
	private static NRTManager nrtManager;
	private static SearcherManager searcherManager;
	private static Directory directory;

	private static String indexPath= PropertyUtils.getProperty ("config","index.path");

	public static LuceneContext getInstance(){

		if (instance==null) {
			init();
			instance=new LuceneContext ();
		}

		return instance;
	}

	private static void init(){

		try {
			directory= FSDirectory.open (new File (indexPath));//索引文件存放路径
			version= Version.LUCENE_35;
			analyzer=new SimpleAnalyzer (LuceneContext.class.getClassLoader ().getResource ("data").getPath ());

			writer=new IndexWriter (directory,new IndexWriterConfig (version,analyzer));

			nrtManager=new NRTManager (writer, new SearcherWarmer () {
				@Override
				public void warm (IndexSearcher indexSearcher) throws IOException {

				}
			});

			searcherManager=nrtManager.getSearcherManager (true);

			NRTManagerReopenThread reopenThread=new NRTManagerReopenThread (nrtManager,5.0,0.025);

			reopenThread.setName ("NRTManager reopen thread");
			reopenThread.setDaemon (true);
			reopenThread.start ();
		} catch (IOException e) {
			e.printStackTrace ();
		}

	}



	public IndexSearcher getSearcher(){
		return searcherManager.acquire ();
	}


	public void releaseSearcher(IndexSearcher searcher){
		try {
			searcherManager.release (searcher);
		} catch (IOException e) {
			e.printStackTrace ();
		}
	}

	public void commitIndex(){
		try {
			writer.commit ();
			writer.forceMerge (3);
		} catch (IOException e) {
			e.printStackTrace ();
		}
	}


	public NRTManager getNrtManager(){
		return nrtManager;
	}

	public Version getVersion(){
		return version;
	}

	public Analyzer getAnalyzer () {
		return analyzer;
	}

	public static void reloadWords(){
		Dictionary.clear (LuceneContext.class.getClassLoader ().getResource ("data").getPath ());
		Dictionary.getInstance (LuceneContext.class.getClassLoader ().getResource ("data").getPath ());
	}
}
